package com.springboot.fast.controller.front;

import com.springboot.fast.model.dto.ResultResponse;
import com.springboot.fast.model.enums.ResultTypeEnum;
import com.springboot.fast.model.qo.JavaComileQO;
import com.springboot.fast.model.service.IJavaComileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/front/compile")
public class FrontJavaComileController {
    @Autowired
    IJavaComileService javaComileService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String comile() {
        return "front/compile";
    }


    /**
     * @param javaComileQO
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultResponse complie(@RequestBody JavaComileQO javaComileQO) {

        System.out.println("javaSource:  " + javaComileQO.getJavaSource());
        try {
            if (StringUtils.isEmpty(javaComileQO.getJavaSource())) {
                return ResultResponse.Build(ResultTypeEnum.error, "代码不能为空！");
            }
            Class clazz = javaComileService.complie(javaComileQO.getJavaSource(), "Test");
            String[] args = getInputArgs(javaComileQO.getExcuteArgs());
            if (null == javaComileQO.getExcuteTimeLimit() && null == args) {
                //无参数 无时限
                return javaComileService.excuteMainMethod(clazz);
            } else if (null == javaComileQO.getExcuteTimeLimit()) {
                //有参数 无时限
                return javaComileService.excuteMainMethod(clazz, args);
            } else if (null == args) {
                //无参数 有时限
                if (javaComileQO.getExcuteTimeLimit() <= 0) {
                    return ResultResponse.Build(ResultTypeEnum.error, "限制时间不能小于1毫秒！");
                }
                return javaComileService.excuteMainMethod(clazz, javaComileQO.getExcuteTimeLimit());
            } else {
                //有参数 有时限
                if (javaComileQO.getExcuteTimeLimit() <= 0) {
                    return ResultResponse.Build(ResultTypeEnum.error, "限制时间不能小于1毫秒！");
                }
                return javaComileService.excuteMainMethod(clazz, javaComileQO.getExcuteTimeLimit(), args);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultResponse.Build(ResultTypeEnum.error, "编译出错了！ 错误信息:" + e.getMessage());
        }
    }

    /**
     * 获取运行时程序需要的参数
     *
     * @param excuteArgsStr 参数字符串
     */
    private String[] getInputArgs(String excuteArgsStr) {
        if (StringUtils.isEmpty(excuteArgsStr)) {
            return null;
        } else {
            return excuteArgsStr.split(" ");
        }
    }
}
